/*
 * ============================================================================
 *
 *       Filename:  main.c
 *
 *    Description:  
 *
 *        Version:  1.0
 *        Created:  2016年09月17日 16时18分36秒
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  xiaojian jiang (Adams), linfeng2010jxj@163.com
 *   Organization:  
 *
 * ============================================================================
 */
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <unistd.h>
#include <sys/file.h>
#include <sys/reboot.h>
#include <errno.h>
#include <stdlib.h>

#include "config.h"
#include "md5.h"

#define WAITTIME (300)
#define RETRYTIME (3600)

#if MD5POS == CPUID
#define ARTMD5 	"echo -n `dmidecode  -t 4 | grep ID | awk NR==1 | awk -F'ID:' '{print $2}' | sed 's/ //g' | md5sum | awk '{print $1}'`"
#warning "uboot md5sum"
#elif MD5POS == MAC
#define ARTMD5  "echo -n `ifconfig eth0 | grep 'HWaddr' | awk NR==1 | awk -F 'HWaddr ' '{print $2}' | sed 's/://g' | md5sum | awk '{print $1}'`"
#warning "eth0 mac(no ':') md5sum"
#elif MD5POS == SATASN
#define ARTMD5  "echo -n `hdparm -i /dev/sda | grep 'SerialNo' | awk NR==1 | awk -F'SerialNo=' '{print $2}' | md5sum | awk '{print $1}'`"
#warning "Disk ID md5sum"
#else
#error	"Please specify md5sum position"
#endif

#define SETID 	"uci set system.@system[0].id=%s;uci commit"
#define GETAUTH "uci get system.@system[0].auth"
#define SETAUTH "uci set system.@system[0].status=1;uci set system.@system[0].authword='已授权';uci commit"
#define SETNOAUTH "uci set system.@system[0].status=0;uci set system.@system[0].authword='未授权';uci commit"
#define HALT1 "richard"
#define HALT2 "adams"

static int get_cmd_stdout(char *cmd, char *buf, int len)
{
	FILE *fp;
	int size;
	fp = popen(cmd, "r"); 
	if(fp != NULL) {
		size = fread(buf, 1, len, fp);
		if(size <= 0)
			goto err;
		buf[len - 1] = 0;
		/*  skip \n */
		if(buf[size - 1] == '\n') {
			buf[size - 1] = 0;
			size--;
		}
		pclose(fp);
		return size;
	}
err:
	buf[0] = 0;
	return -1;
}

static char *getartmd5()
{
	static char artmd5[33] = {0};
	if(get_cmd_stdout(ARTMD5, artmd5, 33) < 0)
		return NULL;
	return artmd5;
}

static void setid(char *key)
{
	char command[1024];
	sprintf(command, SETID, key);
	system(command);
}

int auth()
{
	int i, retry;
	char *artmd5;
	char decryptstr[33] = {0};
	unsigned char decrypt[16];
	MD5_CTX md5;
	if((artmd5 = getartmd5()) == NULL) {
		return 0;
	}
	setid(artmd5);
	char systemauth[33];
	get_cmd_stdout(GETAUTH, systemauth, 33);

	MD5Init(&md5);
	MD5Update(&md5, HALT1, strlen(HALT1));
	MD5Update(&md5, artmd5, strlen(artmd5));
	MD5Update(&md5, HALT2, strlen(HALT2));
	MD5Final(&md5, decrypt);
	for(i = 0; i < 16; i++)
		sprintf(decryptstr + i*2, "%02x", decrypt[i]);

	if(!strncmp(decryptstr, systemauth, 33)) {
		system(SETAUTH);
		return 1;
	}
	system(SETNOAUTH);
	return 0;
}

